package cn.bonoon.kernel.util;

import org.apache.commons.codec.binary.Base64;

public abstract class CryptoUtil {
	protected CryptoUtil() { }

	/** 默认的密码字符串组合，apache校验下载的文件的正确性用的就是默认的这个组合 */
	protected final static char hexDigits[] = { 
		'0', '1', '2', '3', '4', '5', '6', '7', 
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 
	};
	
	protected static String toBase64(byte bytes[]){
		return Base64.encodeBase64String(bytes);
	}

	protected static String toHex(byte bytes[]) {
		return toHex(bytes, 0, bytes.length);
	}

	protected static String toHex(byte bytes[], int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;
		for (int l = m; l < k; l++) {
			appendHex(bytes[l], stringbuffer);
		}
		return stringbuffer.toString();
	}

	protected static void appendHex(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 0xf0) >> 4];
		char c1 = hexDigits[bt & 0xf];
		stringbuffer.append(c0).append(c1);
	}

	protected static final byte[] toBytes(String s) {
		byte[] bytes = new byte[s.length() / 2];
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
		}
		return bytes;
	}
}
